package com.chenchao.reflection;

import java.lang.reflect.Method;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/2 18:41
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.reflection.Test10.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 性能测试
 */
public class Test10 {
    public static final long COUNT=10_0000_0000;
    public static void main (String[] args) throws Exception{
        User user = new User();
        test01(user);
        test02(user);
        test03(user);
    }

    /**
     * 以普通方式访问一亿次对象
     */
    public static void test01(User user){
        long startTime = System.currentTimeMillis();

        for (long i = 0; i < COUNT; i++) {
            user.setName("");
        }
        System.out.println("以普通方式访问一亿次对象需要"+
                (System.currentTimeMillis()-startTime)+"ms");
    }
    /**
     * 以反射方式访问一亿次对象
     */
    public static void test02(User user) throws Exception {
        Class aClass = Class.forName("com.chenchao.reflection.User");
        Method setName = aClass.getMethod("setName", String.class);
        long startTime = System.currentTimeMillis();
        for (long i = 0; i < COUNT; i++) {
            setName.invoke(user,"");
        }
        System.out.println("以反射方式访问一亿次对象需要"+
                (System.currentTimeMillis()-startTime)+"ms");
    }
    /**
     *关闭访问监测， 以反射方式访问一亿次对象
     */
    public static void test03(User user) throws Exception {
        Class aClass = Class.forName("com.chenchao.reflection.User");
        Method setName = aClass.getMethod("setName", String.class);
        setName.setAccessible(true);
        long startTime = System.currentTimeMillis();
        for (long i = 0; i < COUNT; i++) {
            setName.invoke(user,"");
        }
        System.out.println("关闭访问监测， 以反射方式访问一亿次对象需要"+
                (System.currentTimeMillis()-startTime)+"ms");
    }
}
class User{
    private  String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }
}